﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Chinesys.Domain.Helpers
{
    public static class SerializationHelper
    {
        public static void XmlSerialize<T>(T obj, string path)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            Stream stream = new FileStream(path, FileMode.Create);
            serializer.Serialize(stream, obj);
        }

        public static T XmlDeserialize<T>(string path)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            Stream stream = new FileStream(path, FileMode.Open);
            return (T)serializer.Deserialize(stream);
        }

        public static void BinarySerialize(object obj, string path)
        {
            using (Stream stream = new FileStream(path, FileMode.Create))
            {
                BinaryFormatter serializer = new BinaryFormatter();
                serializer.Serialize(stream, obj);
            }
        }

        public static object BinaryDeserialize(string path)
        {
            object ret;

            using (Stream stream = new FileStream(path, FileMode.Open))
            {
                BinaryFormatter serializer = new BinaryFormatter();
                ret = serializer.Deserialize(stream);
            }

            return ret;
        }

        public static void GenerateTextFile(string path, string text)
        {
            using (StreamWriter stream = new StreamWriter(path))
            {
                stream.Write(text);
            }
        }

    }
}
